内存 HttpServer 处理程序
Christian Stein 于 2023 年 11 月 6 日受 JEP 408 摘要的启发,该摘要写道
摘要 提供一个命令行工具来启动一个最小化的 Web 服务器,该服务器在当前目录中提供静态文件。此低门槛实用程序将对原型设计、临时编码和测试目的非常有用,尤其是在教育环境中。
这是一个在内存中提供服务的 http 处理程序实现。这对于运行想要对一组已知资产发出 GET 或 HEAD 请求的 http 客户端测试非常有用。
资产
资产记录封装了 http 返回代码、要发送的字节以及用作 Content-Type
响应头的类型组件。
public record Asset(int code, byte[] data, String type) {
public static Asset of(byte... bytes) {
return new Asset(200, bytes, "application/octet-stream");
}
public static Asset ofBase64(String base64, String type) {
return new Asset(200, Base64.getDecoder().decode(base64), type);
}
public static Asset ofHtml(String html) {
return Asset.ofText(200, html, "text/html");
}
public static Asset ofText(String text) {
return Asset.ofText(200, text, "text/plain");
}
public static Asset ofText(int code, String text, String type) {
return new Asset(code, text.getBytes(StandardCharsets.UTF_8), type);
}
// ... here be more convenient factory methods
}
所有已知资产都组织在一个 Map<String, Asset>
中,使用绝对请求路径作为键。
Map<String, Asset> createAssets() {
return Map.of(
"/index.text", Asset.ofText("Index"),
"/index.html", Asset.ofHtml(
"""
<html>
<body>
<h1>Index</h1>
</body>
</html>
""")
// ... here be more path-asset mappings
);
}
默认情况下,所有表示目录的路径(以 /
结尾)都映射到一个生成目录列表的资产。所有其他未映射的路径(非目录)都映射到一个呈现 404 错误页面的资产。
命令行演示
通过以下方式在命令行上启动内存 http 服务器演示
$ java InMemoryHttpServer.java
> InMemoryHttpServer
> http://127.0.0.1:59476
在浏览器中打开 URL